#include "toolkit.h"
#include <QHostAddress>
#include <QNetworkInterface>

const char* TK::socketTypeName(bool tcp)
{
    return tcp ? "TCP" : "UDP";
}

QString TK::ipstr(const QHostAddress& addr, quint16 port)
{
    return addr.toString() + ':' + QString::number(port);
}

QString TK::bin2hex(const char* buf, uint len)
{
    if (!buf || len == 0) return "";
    
    QString result;
    result.reserve(len * 3);
    
    for (uint i = 0; i < len; ++i) {
        unsigned char c = static_cast<unsigned char>(buf[i]);
        result += QString("%1%2 ").arg(hextab[(c >> 4) & 0xF]).arg(hextab[c & 0xF]);
    }
    
    return result.trimmed();
}

QString TK::bin2ascii(const char* buf, uint len)
{
    if (!buf || len == 0) return "";
    
    QString result;
    result.reserve(len);
    
    for (uint i = 0; i < len; ++i) {
        unsigned char c = static_cast<unsigned char>(buf[i]);
        result += (c >= 32 && c <= 126) ? QChar(c) : QChar('.');
    }
    
    return result;
}

bool TK::ascii2bin(const QString& src, QByteArray& dst, QString& err)
{
    dst.clear();
    err.clear();
    
    // 简化的实现，只处理十六进制字符串
    QString hexStr = src.trimmed();
    if (hexStr.startsWith('[') && hexStr.endsWith(']')) {
        hexStr = hexStr.mid(1, hexStr.length() - 2);
    }
    
    QStringList hexParts = hexStr.split(' ', Qt::SkipEmptyParts);
    
    for (const QString& part : hexParts) {
        bool ok;
        int value = part.toInt(&ok, 16);
        if (!ok || value < 0 || value > 255) {
            err = QString("Invalid hex value: %1").arg(part);
            return false;
        }
        dst.append(static_cast<char>(value));
    }
    
    return true;
}

char* TK::createBuffer(qint64& cap, qint64 limit)
{
    if (cap < 0 || cap > limit) {
        return nullptr;
    }
    
    if (cap == 0) {
        cap = 1;
    }
    
    return new char[static_cast<size_t>(cap)];
}

void TK::releaseBuffer(char*& buf)
{
    delete[] buf;
    buf = nullptr;
}

const char* TK::hextab = "0123456789ABCDEF"; 